#!/home1/tomorrp1/bin/python2.7
# coding: utf-8
'''
Created on 2011-5-8

@author: sevear
'''
import web,p2p;
import model;
import errconst;
import json;
import chaosdb;
import re;
import event;
import util;
import urllib;
from net.sevear.douban.DBUserAPI import DBUserAPI

CONTACTS_MAX = 6;

class Contacts2:
    def GET(self):
        input = web.input();
        if(hasattr(input, 'uid')):
            rst = {"errcode":0,"errmsg":"ok","content":getContacts(int(input.uid))}
            return json.dumps(rst);
        else:
            return util.generateErr(errconst.OPERATION_WITHOUT_UID);
    
    def POST(self):
        input = web.input();
        if(hasattr(input, 'uid')):
            uid = input.uid;
            if(hasattr(input, "op")):
                op = input.op;
                if(op=="a"):
                    uidStr = input.aliass;
                    alialist = json.loads(uidStr);
                    if(alialist==None or len(alialist)==0):
                        alialist = uidStr.split('|');
                    return addContacts(int(uid), alialist);
                elif(op == "d"):
                    uidStr = input.uids;
                    uids = str(uidStr).split('|');
                    return deleteContacts(int(uid), uids);
                elif(op == "i"):
                    invite(int(uid),int(input.invitetedid), input.name, input.alias, input.url, input.headimg);
                    rst = {"errcode":0,"errmsg":"ok","content":getContacts(int(input.uid))}
                    return json.dumps(rst);
            return errconst.OP_CONTACTS_WITHOUT_OP;
        else:
            return errconst.GET_USER_INFO_WITHOUT_UID;
        
def getContacts(uid):
    return json.dumps(chaosdb.getDBUserContacts(uid));


def invite(inviterid,uid,name,alias,url,headimg):
    dbUser = model.getUser(uid);
    if(dbUser!=None and dbUser.isactivate==1):
        pass
    elif(dbUser!=None and dbUser.isactivate==0):
        alialist = [str(uid)];
        return addContacts(inviterid, alialist);
    else:
        chaosdb.addUnActivateUser(uid,name,alias,url,headimg);
        alialist = [str(uid)];
        return addContacts(inviterid, alialist);

def getQuickList(id):
    listStr = chaosdb.getContactListStr(id);
    if(listStr=='' or listStr==None):
        lists = [];
    else:
        lists = listStr.split(',');
    return lists

def addContacts(id,alialist):
    lists = getQuickList(id)
        
    if(len(alialist)+len(lists)>CONTACTS_MAX):
        return util.generateErr(errconst.ADD_EXCEED_MAX);
    
    eventUIDs=[];
    for addAlias in alialist:
        addAlias = urllib.unquote_plus(addAlias);
        addUser = searchUser(addAlias);
        if(addUser==None):
            usersByName = chaosdb.getDBUserByNames(addAlias);   
            if(len(usersByName)==1):
                addUser =  usersByName[0];
                if((str(addUser.uid) in lists)==True):
                    return util.generateErr(errconst.ADD_HASADDED_ITEM);
                else:
                    eventUIDs.append(addUser.uid);
                    lists.append(str(addUser.uid));
                    p2p.addSite(id, addUser.uid)
            elif(len(usersByName)==0):
                return util.generateErr(errconst.ADD_NONE_EXIST_CONTACT_ITEMS);
            else:
                samelist = [];
                for sameNameUser in usersByName:
                    if(len(samelist)<=10):
                        samelist.append({"uid":sameNameUser.uid,
                                     "activietime":sameNameUser.activietime.strftime("%Y-%m-%d %H:%M:%S")
                                     ,"uidstr":sameNameUser.dbuid
                                     ,"dburl":sameNameUser.dburl
                                     ,"headimg":sameNameUser.headimg,
                                     "name":sameNameUser.name});
                errrst = {"errcode":errconst.ADD_USERS_WITH_SAME_NAME,"errmsg":"","content":json.dumps(samelist)}
                return json.dumps(errrst); 
        else:
            if((str(addUser.uid) in lists)==True):
                return util.generateErr(errconst.ADD_HASADDED_ITEM);
            else:
                if(needAddEvent(id, addUser.uid,addUser)):
                    eventUIDs.append(addUser.uid);
                lists.append(str(addUser.uid));
                p2p.addSite(id, addUser.uid)

                
    chaosdb.updateContacts(id, ','.join(lists));
    sourceUser = model.getUser(id);
    if(sourceUser!=None):
        for eventUID in eventUIDs:
            event.addEvent(eventUID,event.TYPE_ADD_AS_FROM_ID,
                           "[type=user,id=%d,display=%s]添加你为Chaos推荐对象了"%(id,sourceUser.name));
    rst = {"errcode":0,"errmsg":"ok","content":getContacts(id)}
    return json.dumps(rst);

def needAddEvent(id,toid,toUser):
    if(id == toid):
        return False
    
    if(toUser!=None):
        if(toUser.sendlist!=None and toUser.sendlist!=""):
            toUserContactList = str(toUser.sendlist).split(',')
            return (str(id) in toUserContactList)==False
        return True
    return True

def searchUser(userKey):
    addUser = chaosdb.getDBUserByAlias(userKey);
    if(addUser==None):
        print re.match(r'[+-]?\d+$',userKey);
        if re.match(r'[+-]?\d+$',userKey):
            addUser = model.getUser(int(userKey));
        else:
            api = DBUserAPI()
            return api.searchDBUser(userKey)
    return addUser;

def deleteContacts(uid,idss):
    lists = getQuickList(uid)
    newlists = [];
    for existid in lists:
        if((existid in idss)==False):
            newlists.append(existid);
    chaosdb.updateContacts(uid, ','.join(newlists))
    for deleteid in idss:
        p2p.removeSite(uid, int(deleteid))
    rst = {"errcode":0,"errmsg":"ok","content":getContacts(uid)}
    return json.dumps(rst);
